package com.huiyang.demo.service;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.util.Log;


import static android.content.Context.BIND_AUTO_CREATE;

/**
 * @ProjectName: DEEBCG Websoket Demo
 * @Package: com.clock.blelib.service
 * @ClassName: WebSocketUtil
 * @Description: java类作用描述
 * @Author: yuan
 * @CreateDate: 2020/10/15 4:43 PM
 */
public class WebSocketUtil {

    private Context context;

    static WebSocketUtil webSocketUtil = null;

    private WebSocketService myService = null;
    private IWebSocketResponseListener listener = null;
    private boolean isStartService = false;//service是否开启

    public WebSocketUtil(Context context) {
        this.context = context;
    }

    public static synchronized WebSocketUtil getInstance(Context context) {
        if (webSocketUtil == null) {
            webSocketUtil = new WebSocketUtil(context);
        }
        return webSocketUtil;
    }

    public void closeSocket() {
        if (myService != null) {
            myService.closeSocket();
        }
    }

    ServiceConnection connection;

    /**
     * 开启socket
     *
     * @param listener
     */
    public void startSocket(IWebSocketResponseListener listener,String id) {
        this.listener = listener;
        if (isStartService && myService != null) {
            //service开启 只需执行登录 无需再启动service
            myService.againLoginConnection(id);
            return;
        }
        connection = new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
                myService = ((WebSocketService.MyBinder) service).getService();
                myService.setResponseListener(listener);
                myService.setEquipmentNumber(id);
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
                Log.e("MyApplication", "service disconnected.");
            }
        };
        Intent intent = new Intent(context, WebSocketService.class);
        context.bindService(intent, connection, BIND_AUTO_CREATE);
        isStartService = true;
    }

    public void unbind() {
        if (myService != null)
            context.unbindService(connection);
    }

}
